
//
//  JSSEmoticonpPageCell.swift
//  WeiBoItem
//
//  Created by jss on 16/4/28.
//  Copyright © 2016年 jss. All rights reserved.
//

import UIKit


class JSSEmoticonpPageCell: UICollectionViewCell {
    
    //给cell设置表情数据的数组
    var emoticons:[JSSEmoticonModel]? {
        
        didSet{
            guard let emo = emoticons else{
                return
            }
            
            
            //防止cell重用时 图片显示重复的
            //先隐藏所有的btn(遍历按钮数组)（因为涉及到复用，所以我们需要设置一个表情就显示一个表情）
            for value in emoticonBtnArray {
                
                value.hidden = true
            }
           
            //遍历传进来的数组
            for (index,emoticon) in emo.enumerate() {
                
                //取出btn
                let btn = emoticonBtnArray[index]
                
                btn.hidden = false
                
                btn.emoticon = emoticon

                
//                if emoticon.type == "1" {
//                  //如果类型是1 代表是emoji表情
//                    btn.setTitle((emoticon.code! as NSString).emoji(), forState: UIControlState.Normal)
//                    btn.setImage(nil, forState: UIControlState.Normal)
//                    
//                }else{
//                    
//                    //设置数据
//                    let image = UIImage(named: "\(emoticon.folderName ?? "")/\(emoticon.png ?? "")", inBundle: JSSEmoticonkeyboardViewModel.EmoticonkeyboardSharedViewModel.emoticonBundle, compatibleWithTraitCollection: nil)
//                    
//                    btn.setImage(image, forState: .Normal)
//                    btn.setTitle(nil, forState: UIControlState.Normal)
//                }
            }
        
        }
    }
    
    //定义一个数组  用来记录每页的添加的表情按钮
    var emoticonBtnArray:[JSSEmoticonPopButton] = []
    
    
    var indexPath: NSIndexPath? {
        
        didSet {
        
            self.messageLabel.hidden = self.indexPath?.section != 0
            //self.label.text = "第\(indexPath?.section ?? 0)组,第\(indexPath?.item ?? 0)页"
        
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func  setupUI() {
    
     contentView.addSubview(messageLabel)
    
        messageLabel.snp_makeConstraints { (make) -> Void in
            
            make.centerX.equalTo(contentView)
            make.bottom.equalTo(contentView).offset(-10)
            
        }
        
        //添加表情按钮
        self.addChildBtn()
 
        //添加删除按钮
        self.contentView.addSubview(deleteBtn)
        
        //给contentView添加手势
        let longPress = UILongPressGestureRecognizer(target: self, action: "longPress:")
        
        //测试 给个最短的触发时间
        //longPress.minimumPressDuration = 2
        
        contentView.addGestureRecognizer(longPress)
    }
    
    //实现长按手势方法
    @objc private func longPress(longPress:UILongPressGestureRecognizer){
        
        //取到手指触摸位置
        let loc = longPress.locationInView(longPress.view)
        
        //print(loc)
        
        //找到该手势对应的按钮
        func btnWithLoc(loc:CGPoint)->JSSEmoticonPopButton? {
        
            for value in emoticonBtnArray {
                
                //如果value的范围内包含传入的点 直接返回
                if CGRectContainsPoint(value.frame, loc){
                    
                    return value
                }
            }
            return nil
        }
        
        //通过点找到点相对应的表情按钮
        guard let button = btnWithLoc(loc) else {
            
            popView.removeFromSuperview()
            return
        }
        
        switch longPress.state {
            
        case .Began,.Changed:
            //取到最上层的window
            let window = UIApplication.sharedApplication().windows.last!
            //坐标转换
            let rect = button.superview!.convertRect(button.frame, toView: window)
            
            //中心点
            popView.center.x = CGRectGetMidX(rect)
            popView.frame.origin.y = CGRectGetMaxY(rect) - popView.frame.height
            //给popView里面的按钮赋值
            popView.emoticonbtn.emoticon = button.emoticon
            
            window.addSubview(popView)
        default:
            popView.emoticonbtn.emoticon = nil
            popView.removeFromSuperview()
        }
        
        print("此手势方法被执行了")
    }
    
            
    //布局添加的btn
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let w = self.frame.width / CGFloat(JSSEmoticonkeyboardMaxCol)
        
        let h =  (self.frame.height - 25) / CGFloat(JSSEmoticonkeyboardMaxRow)
        
        //调整20个按钮的位置(x值和y值)
        for (index,value) in emoticonBtnArray.enumerate(){
        
        //九宫格算法
            //求得列索引
            let col = index % JSSEmoticonkeyboardMaxCol
            
            //求得行索引
            let row = index / JSSEmoticonkeyboardMaxCol
            
            //设置btn的位置
            let x = CGFloat(col) * w
            let y = CGFloat(row) * h
            
            value.frame = CGRectMake(x, y, w, h)
        
            self.deleteBtn.frame = CGRectMake(self.frame.width - w, self.frame.height - h - 25, w, h)
        
        }
        
    }
    
    //cell添加20个表情按钮(表情按钮(btn))
    
    private func addChildBtn(){
        
        let btnCountMax = JSSEmoticonkeyboardPageEmoticonCount
        
        //循环添加按钮
        
        for _ in 0..<btnCountMax {
            
            let btn = JSSEmoticonPopButton()
            
            //给表情按钮添加点击事件
            btn.addTarget(self, action: "emoticonBtnDidClick:", forControlEvents: UIControlEvents.TouchUpInside)
            
            //设置Emoji表情的字体大小
            btn.titleLabel?.font = UIFont.systemFontOfSize(35)
            
//            btn.backgroundColor = randomColor
            
            //把btn添加到cell的contentView上
            self.contentView.addSubview(btn)
            
            //把添加的表情按钮添加到数组里
            self.emoticonBtnArray.append(btn)
            
        }
        
    }
    
    
    //实现表情按钮的点击事件
    @objc private func emoticonBtnDidClick(btn:JSSEmoticonPopButton) {
    
       print(btn.emoticon?.chs)//证明成功取到表情对应的文字
        
        
        //保存最近表情
        JSSEmoticonkeyboardViewModel.EmoticonkeyboardSharedViewModel.saveRencentEmoticon(btn.emoticon!)
        
        //点击发送通知 把相应的表情显示到textView上
        NSNotificationCenter.defaultCenter().postNotificationName(JSSEmoticonBtnClickNotification, object: nil, userInfo: ["emoticon":btn.emoticon!])
        
        //取到最上层的window
        let window = UIApplication.sharedApplication().windows.last
        
        //初始化一个popView
        // let popView = JSSEmoticonPopView.popView()
        
        //设置当前popView的位置
        //坐标转换: 将按钮在contentView里的坐标转换成在window上的坐标(convweRect:  XX.convertRect(XX,toView:XX)
        let rect = btn.superview!.convertRect(btn.frame, toView: window)
        
        //中心点
        popView.center.x = CGRectGetMidX(rect)
        
        popView.frame.origin.y = CGRectGetMaxY(rect) - popView.frame.height
        
        
        //给popView里面的btn赋值
        popView.emoticonbtn.emoticon = btn.emoticon
        
        window?.addSubview(popView)
        
        
        //多少秒后自己从父view上移除
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.3 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            
            self.self.popView.removeFromSuperview()
        }
        
     
    }
    
 
    //实现删除按钮的点击事件
    @objc private func emoticonDeleteBtnDidClick(){
        
        // print("删除按钮被点击了")
        //发出通知 点击删除按钮的时候 相对应的textView上也删除一个字符
        NSNotificationCenter.defaultCenter().postNotificationName(JSSEmoticonDeleteBtnClickNotification, object: nil)
        
    }
    
  //添加delete按钮
    private lazy var deleteBtn:UIButton = {
        
        let btn = UIButton()
        
        //给删除按钮添加监听事件
        btn.addTarget(self, action: "emoticonDeleteBtnDidClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        btn.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
        btn.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
        
        return btn
        
    }()
    
    
    //添加消息lable
    private lazy var messageLabel: UILabel = {
    
        let lab = UILabel(textColor: UIColor.darkGrayColor(), textFont: 14)
        
        lab.text = "最近使用表情"
        
        return lab
    
    }()
    
    
    //长按出现的popView
    private lazy var popView:JSSEmoticonPopView = {
     let popView = JSSEmoticonPopView.popView()
        
        return popView
    
    }()
    
    
}
